#include "FWGame.h"


FWGame::FWGame(HINSTANCE hIns, char* windowName, int _Width,int _Height)
{
	this->hInstance = hIns;	
	this->Height = _Height;
	this->Width = _Width;
	Name = new char[strlen(windowName)];
	strcpy(Name,windowName);
	d3ddev = NULL;
	d3d = NULL;
}


FWGame::~FWGame(void)
{
}

bool FWGame::InitWindow()
{
	WNDCLASSEX wndclass;
	wndclass.cbSize = sizeof(WNDCLASSEX);
	wndclass.cbClsExtra = 0;
	wndclass.cbWndExtra = 0;
	wndclass.hIconSm = 0;
	wndclass.hIcon = 0;
	wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wndclass.hCursor = LoadCursor(NULL,IDC_ARROW);
	wndclass.hInstance = this->hInstance;
	wndclass.lpfnWndProc = (WNDPROC)WinProc;
	wndclass.lpszClassName = "Game";
	wndclass.lpszMenuName = NULL;
	wndclass.style = CS_HREDRAW | CS_VREDRAW;

	if(!RegisterClassEx(&wndclass))
	{
		return false;
	}
	this->hwnd = CreateWindow(
		"Game",//ten class dang ki cua so
		this->Name,// ten cua so
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		this->Width,
		this->Height,
		NULL,
		NULL,
		this->hInstance,
		NULL);
	if(!this->hwnd)
		return false;
	ShowWindow(this->hwnd,SW_NORMAL);
	UpdateWindow(this->hwnd);
	return true;
}
bool FWGame::InitDX()
{
	//tao doi tuong dx
	this->d3d = Direct3DCreate9(D3D_SDK_VERSION);
	if(d3d == NULL)
	{
		return false;
	}

	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp,sizeof(d3dpp));
	//dinh nghia man hinh
	d3dpp.BackBufferCount = 1;
	d3dpp.BackBufferFormat = D3DFORMAT::D3DFMT_UNKNOWN;
	d3dpp.Windowed = true;
	d3dpp.BackBufferHeight = this->Height;
	d3dpp.BackBufferWidth = this->Width;
	d3dpp.SwapEffect = D3DSWAPEFFECT::D3DSWAPEFFECT_DISCARD;
	d3dpp.hDeviceWindow = this->hwnd;
	//Tao thiet bi

	HRESULT hr = d3d->CreateDevice(D3DADAPTER_DEFAULT,//chon card man hinh
								D3DDEVTYPE::D3DDEVTYPE_HAL,//loai thiet bi
								this->hwnd,//cua so game
								D3DCREATE_SOFTWARE_VERTEXPROCESSING,
								&d3dpp,//thong so card
								&this->d3ddev//out bien kiem soat card man hinh
		);
	if(FAILED(hr))
	{
		return false;
	}
	return true;
}
void FWGame::Load()
{

}

HRESULT CALLBACK FWGame::WinProc(HWND hwnd,UINT	message, WPARAM wParam,LPARAM lParam)
{
	if(message == WM_DESTROY)
	{
		PostQuitMessage(0);
	}
	return DefWindowProc(hwnd,message,wParam,lParam);
}

void FWGame::Run()
{
	MSG msg;
	ZeroMemory(&msg,sizeof(MSG));
	while(msg.message != WM_QUIT)
	{		
		if(PeekMessage(&msg,NULL,NULL,NULL,PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{			
			this->Render();
		}
	}
}

void FWGame::Render()
{
	this->d3ddev->Clear(1,NULL,D3DCLEAR_TARGET,D3DCOLOR_XRGB(0,255,255),1,NULL);
	this->d3ddev->Present(NULL,NULL,NULL,NULL);
}